<template>
  <div class="tableListBox">
    <div class="common-header">
      <div style="cursor: pointer" @click="back">
        <i class="vxe-icon-arrow-left" style="vertical-align: middle"></i
        ><span style="vertical-align: middle">返回</span>
      </div>
      <div>
        <el-button type="primary" size="small" @click="edit">编辑</el-button>
      </div>
    </div>
    <div class="anthorContent">
      <p class="title"><span class="titleName">基础信息</span></p>
      <vxe-form :data="form" title-align="right" class-name="outForm">
        <vxe-form-item title="收费标准版本" field="versionName" :item-render="{}">
          <template #default="{ data }">
            <vxe-input
              v-model="data.versionName"
              class="normal"
              placeholder="收费标准版本"
              disabled
              clearable
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item title="制定日期" field="pubts" :item-render="{}">
          <template #default="{ data }">
            <vxe-input
              :value="parseTime(data.pubts, '{y}-{m}-{d}')"
              class="normal"
              placeholder="制定日期"
              disabled
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item title="当前状态" field="isEnabled" :item-render="{}">
          <template #default="{ data }">
            <vxe-select :value="!!data.isEnabled" placeholder="当前状态" disabled>
              <vxe-option :value="true" label="启用"></vxe-option>
              <vxe-option :value="false" label="停用"></vxe-option>
            </vxe-select>
          </template>
        </vxe-form-item>
        <vxe-form-item :visible-method="showFn" title="更新人" field="modifierName" :item-render="{}">
          <template #default="{ data }">
            <vxe-input v-model="data.modifierName" class="normal" placeholder="更新人" disabled></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item :visible-method="showFn" title="更新时间" field="modifyTime" :item-render="{}">
          <template #default="{ data }">
            <vxe-input v-model="data.modifyTime" class="normal" placeholder="更新时间" disabled></vxe-input>
          </template>
        </vxe-form-item>
      </vxe-form>
      <p class="title">
        <span class="titleName">收费标准详情</span>
      </p>
      <div class="title-operation">
        <el-button type="primary" size="small" @click="getExport">导出</el-button>
      </div>
      <TableCommon ref="common" :columns="tableColumn" :tableData="commonTableData" />
    </div>
    <!-- 不展示，只是用来导出数据 -->
    <div style="position: fixed; left: -10000px; width: 100%">
      <vxe-table
        ref="xTable"
        resizable
        show-header-overflow
        align="center"
        :data="tableData"
        border
        :merge-cells="mergeCells"
      >
        <vxe-column type="seq" title="序号" width="60" show-overflow></vxe-column>
        <vxe-column field="itemName" title="检测项目" width="120" show-overflow></vxe-column>
        <vxe-column field="itemShortName" title="项目编号拼音简称" show-overflow></vxe-column>
        <vxe-column field="paramName" title="检测参数" show-overflow></vxe-column>
        <vxe-column field="salesUnit" title="计价单位" show-overflow></vxe-column>
        <vxe-column field="unitPrice" title="单价(元)" show-overflow></vxe-column>
        <vxe-column field="domainNames" title="检测领域" width="200" show-overflow></vxe-column>
        <vxe-column field="detectionStds" title="检测标准" width="200" show-overflow></vxe-column>
        <vxe-column field="workingHours" title="工时" show-overflow></vxe-column>
        <vxe-column field="remarks" title="备注" show-overflow></vxe-column>
        <vxe-column field="isEnabled" title="状态" show-overflow>
          <template #default="{ row }">
            <span>{{ row.isEnabled | formatStatus }}</span>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>
<script>
import TableCommon from './common';
import VXETable from 'vxe-table';
import util from '@/util/util';
export default {
  components: { TableCommon },
  data() {
    return {
      form: {
        versionName: '',
        pubts: '',
        isEnabled: false,
        modifierName: '',
        modifyTime: '',
      },
      tableColumn: [
        {
          field: 'name',
          treeNode: true,
          title: '检测项目 / 检测参数',
          editRender: {},
          slots: {
            default: 'd_itemName',
            // edit: 'e_itemName',
          },
        },
        {
          field: 'itemShortName',
          title: '项目编号拼音简称',
          editRender: {},
          slots: {
            // edit: 'e_itemShortName',
            default: 'd_itemShortName',
          },
        },

        {
          field: 'salesUnit',
          title: '计价单位',
          width: 80,
          align: 'center',
          editRender: {},
          slots: {
            // edit: 'e_salesUnit',
            default: 'd_salesUnit',
          },
        },
        {
          field: 'unitPrice',
          title: '单价(元)',
          align: 'center',
          width: 100,
          editRender: {},
          slots: {
            // edit: 'e_unitPrice',
            default: 'd_unitPrice',
          },
        },
        {
          field: 'domainIds',
          title: '检测领域',
          editRender: {},
          slots: {
            // edit: 'e_area',
            default: 'd_area',
          },
        },
        {
          field: 'detectionStdIds',
          title: '检测标准',
          editRender: {},
          slots: {
            // edit: 'e_std',
            default: 'd_std',
          },
        },
        {
          field: 'workingHours',
          title: '工时',
          align: 'center',
          width: 80,
          editRender: {},
          slots: {
            // edit: 'e_workingHours',
            //   default: 'd_hours',
          },
        },
        {
          field: 'remarks',
          title: '备注',
          editRender: {},
          slots: {
            // default: 'd_remark',
          },
        },
        {
          field: 'isEnabled',
          title: '状态',
          align: 'center',
          width: 100,
          editRender: {},
          slots: {
            // edit: 'e_status',
            default: 'd_status',
          },
        },
      ],
      commonTableData: [],
      tableData: [],
      mergeCells: [],
      tableViewH: 400,
    };
  },
  filters: {
    formatStatus(val) {
      return val ? '启用' : '停用';
    },
  },
  async created() {
    this.getQuery();
    this.getList();
  },
  mounted() {
    this.getTableViewH();
    window.onresize = () => {
      return (() => {
        this.$nextTick(() => {
          this.getTableViewH();
        });
      })();
    };
  },
  methods: {
    parseTime: util.parseTime,
    back() {
      jDiwork.closeWin();
      jDiwork.openService('1756521536796753930');
    },
    edit() {
      this.$router.push({ path: '/chargeStand/edit', query: this.form });
    },
    getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      if (!query) {
        query = window.location.hash.split('?')[1];
      }
      if (!query) {
        return;
      }
      var vars = query.split('&');
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (pair[0] == variable) {
          return decodeURIComponent(pair[1]);
        }
      }
      return '';
    },
    getQuery() {
      this.form.infoId = this.getQueryVariable('infoId');
      this.form.versionName = this.getQueryVariable('versionName');
      this.form.pubts = this.getQueryVariable('pubts')
        ? this.parseTime(this.getQueryVariable('pubts'), '{y}-{m}-{d}')
        : '';
      this.form.isEnabled = this.getQueryVariable('isEnabled');
    },
    showFn({ data, field }) {
      return data[field];
    },
    tranform(table) {
      const transformRow = (list, column = 1, row = 0) => {
        let start = 0;
        while (start < list.length) {
          const first = list[start];
          const last = list.lastIndexOf(first);
          if (start !== last) {
            this.mergeCells.push({
              row: start + row,
              col: column,
              rowspan: last - start + 1,
              colspan: 1,
            });
          }
          start = last + 1;
        }
      };
      const itemName = table.flat(1).map((item) => item.itemName);
      transformRow(itemName, 1);
      const itemShortName = table.flat(1).map((item) => item.itemShortName);
      transformRow(itemShortName, 2);
      return table.flat(1);
    },
    // 获取table高度
    getTableViewH() {
      setTimeout(() => {
        try {
          let h = this.$refs.tableView.offsetHeight;
          // debugger
          console.log(this.tableViewH);
          this.tableViewH = h - 45;
        } catch (error) {}
      }, 1000);
    },
    getList() {
      this.$api
        .getChargeStdDetail({
          infoId: this.form.infoId,
        })
        .then((res) => {
          const { chargeStdItemList, modifierName, modifyTime } = res.data;
          this.form.modifierName = modifierName;
          this.form.modifyTime = modifyTime ? this.parseTime(modifyTime, '{y}-{m}-{d}') : '';
          this.commonTableData = chargeStdItemList;
          function flatten(arr = [], parent = {}) {
            return arr.reduce(function (prev, item) {
              if (!item.chargeStdParamList || item.chargeStdParamList.length === 0) {
                return prev.concat({
                  ...item,
                  detectionStds: item.detectionStdList?.map((item) => item.dictValue)?.join('、'),
                  itemShortName: parent.itemShortName,
                });
              } else {
                return prev.concat(flatten(item.chargeStdParamList || [], item));
              }
            }, []);
          }
          this.tableData = this.tranform(flatten([...chargeStdItemList]));
        });
    },
    async getExport() {
      const fixedRow = 1;
      this.$refs.xTable.exportData({
        filename: '收费标准详情',
        sheetName: '收费标准详情',
        type: 'xlsx',
        useStyle: true,
        columnFilterMethod: (column, $columnIndex) => {
          return !(column.$columnIndex === 0);
        },
        sheetMethod: ({ options, workbook, worksheet }) => {
          // 插入标题
          worksheet.insertRow(1, ['收费标准详情']);
          worksheet.mergeCells(1, 1, 1, worksheet._columns.length);
          const fixedIndex = 1;
          this.mergeCells.forEach((mergeCell) => {
            const { row, col, rowspan, colspan } = mergeCell;
            worksheet.mergeCells(
              row + fixedRow + fixedIndex + 1,
              col,
              row + rowspan + fixedIndex + 1,
              col + colspan - 1,
            );
          });
          // 设置所有单元格
          worksheet.eachRow((row) => {
            row._cells.forEach((item) => {
              item.border = {
                top: { style: 'thin', color: { argb: '000000' } },
                left: { style: 'thin', color: { argb: '000000' } },
                bottom: { style: 'thin', color: { argb: '000000' } },
                right: { style: 'thin', color: { argb: '000000' } },
              };
            });
            row.eachCell((cell) => {
              //设置单元格样式
              cell.fill = {
                type: 'pattern',
                pattern: 'thin',
                fgColor: { argb: 'FF000000' },
              };
              cell.font = { color: { argb: 'FF000000' } };
              // 设置自动换行
              cell.alignment = { wrapText: true, vertical: 'middle', horizontal: 'center', indent: 1 };
            });
          });
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
</style>
